package book;

import utils.AnalyzingBook;
import utils.AnalyzingBorrowBook;
import utils.Constant;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Scanner;

public class Library {
    private Book[] books;
    private int countbook;
    private static Library library;
    AnalyzingBorrowBook analyzingBorrowBook = new AnalyzingBorrowBook();
    private final AnalyzingBook analyzingBook = new AnalyzingBook();
    Scanner scanner = new Scanner(System.in);

    //创建对象的同时加载
    public Library(){
        loadAllBook();
    }

    public  static Library  getLibrary(){
        if(library == null)
            library = new Library();
        return library;
    }

    public Book getBooks(int pos) {
        return books[pos];
    }

    public int getCountbook() {
        return countbook;
    }

    private void loadAllBook(){
        try {
            //1.从指定文件中读取文件
            Book[] allBooks = analyzingBook.loadObject(Constant.ALL_FILE_NAMA);
            books = new Book[Constant.CAPACITY];
            //2.判断是否有效书籍为0
            if(allBooks == null){
                countbook = 0;
            }else {
                //3.求实际长度，赋值
                int allBooksLen = allBooks.length;
                if(allBooksLen > books.length){
                    books = new Book[allBooksLen];
                }
                for (int i = 0; i < allBooksLen; i++) {
                    books[i] = allBooks[i];
                }
                //4.修改实际个数
                countbook = allBooksLen;
            }
        }catch (IOException e){
           throw new RuntimeException(e);
        }
    }
    //存储图书:将图书信息存储在指定文件中
    private void storeBook(){
        try{
            analyzingBook.storeBook(books,"allbook.txt");
        }catch(IOException e){
            throw new RuntimeException(e);
        }
    }
    public void add(Book book){
     //1.判段是否可以存储
        int BookLen = books.length;
        if(countbook >= BookLen){
            System.out.println("书架已满，不可增加书架");
            return;
        }
        //2.可以增加书籍
        books[countbook] = book;
        //3.设置书籍id
        book.setBookId(countbook + 1);
        //4.将书籍信息存储到文件中
        storeBook();
        //5.提示上架书籍成功
        System.out.println("书籍:<<" + book.getTitle() +">>已成功增加！");
    }
    //展示图书
    public void displayBook(){
        if(countbook == 0){
            System.out.println("没有图书，不可展示！");
            return;
        }
        System.out.println("--------------------------------------------------------------");
        for (int i = 0; i < countbook; i++) {
            System.out.println(books[i]);
        }
        System.out.println("--------------------------------------------------------------");
    }
    //搜索图书
    public void searchBook(){

        if(countbook == 0) {
            System.out.println("没有图书不可搜索！");
            return;
        }

//        for (int i = 0; i < countbook; i++) {
//            if(id == books[i].getBookId()){
//                System.out.println("-----------------------");
//                System.out.print("找到了，书籍信息如下：");
//                System.out.println("ID:" + id + " 书籍名称：" + books[i].getTitle());
//                System.out.println("-----------------------");
//                return;
//            }
                int pos = searchBookByID();
                System.out.println("-----------------------");
                System.out.print("找到了，书籍信息如下：");
                System.out.println("ID:" + books[pos].getTitle() + " 书籍名称：" + books[pos].getTitle());
                System.out.println("-----------------------");

    }
   public int searchBookByID(){
       System.out.print("请输入需要搜索的ID：");
       int id = scanner.nextInt();
       int i = 0;
        for (; i < countbook; i++) {
            if(id == books[i].getBookId())
                return i;
        }
        System.out.println("ID" + id + "对应的书籍不存在");
        return -1;
    }
    //修改图书
    public void updataBook(int pos){
        //1.加载书籍信息
        loadAllBook();
        //2。更新图书信息
        System.out.print("请输入书名：");
        String bookName = scanner.nextLine();
        System.out.print("请输入作者名称：");
        String auther = scanner.nextLine();
        System.out.print("请输入书籍类型：");
        String category = scanner.nextLine();
        System.out.print("请输入出版年份：");
        int publishYear = scanner.nextInt();
        LocalDate localDate = LocalDate.now();

        Book book1 = new Book(bookName,auther,category,publishYear,localDate);
        int id = books[pos].getBookId();
        books[pos] = book1;
        books[pos].setBookId(id);
        storeBook();
        System.out.println("更新书籍：《" + books[pos].getTitle() +"》成功！");
    }
    //移除图书
    public void removeBook(int pos){
        loadAllBook();
        for (int i = pos;i < countbook - 1;i++){
            books[i] = books[i + 1];
        }
        System.out.println("移除书籍：《" + books[pos].getTitle() +"》成功！");
        books[countbook - 1] = null;
        countbook--;
        storeBook();
    }
    //书籍借阅次数信息展示
    public void borrowedCount(){
        System.out.println("书籍借阅信息如下：");
        System.out.println("--------------------------");
        for (int i = 0; i < countbook; i++) {
            System.out.println("书籍名称：《" +books[i].getTitle()+"》 " + "借阅次数：" + books[i].getBrorrowCount());
        }
        System.out.println("--------------------------");
    }
    //最受欢迎的前K本书籍
    public  void generateBook(){
        System.out.print("请输入需要查询的书籍数：");
        int k = scanner.nextInt();
        if(k > countbook){
            Book[] newbooks = new Book[countbook];
            for (int i = 0; i < countbook; i++) {
                newbooks[i] = books[i];
            }
            Arrays.sort(newbooks);
            System.out.println("图书馆没有" + k + "本书籍，以下展示最受欢迎的前" + countbook + "本书籍！");
            System.out.println("***************************************************************");
            for (int i = 0; i < countbook; i++) {
                System.out.println(newbooks[i]);
            }
            System.out.println("***************************************************************");
        }else{
            Book[] newbooks = new Book[k];
            for (int i = 0; i < k; i++) {
                newbooks[i] = books[i];
            }
            Arrays.sort(newbooks);
            System.out.println("最受欢迎的前" + k +"本书籍信息如下");
            System.out.println("***************************************************************");
            for (int i = 0; i < k; i++) {
                System.out.println(newbooks[i]);
            }
            System.out.println("***************************************************************");
        }
    }
    //查看库存状态
    public void checkInventoryStatus(){
        System.out.println("书籍库存信息如下：");
        System.out.println("________________________________________");
        for (int i = 0; i < countbook; i++) {
            String status = (books[i].getIsBorrowed()?"已借阅" : "未借阅");
            System.out.println("书籍名称：《" + books[i].getTitle() + "》" +" 库存状态：" + status);
        }
        System.out.println("________________________________________");
    }
    //移除上架一年的图书
    public void checkRemoveBook(){
        //1.获取当前程序的时间戳
        long currentTimestamp = System.currentTimeMillis();
        //2.将当前程序的时间戳转为LocalData
        LocalDate localDate = Instant.ofEpochMilli(currentTimestamp).
                atZone(ZoneId.systemDefault()).toLocalDate();
        //3.遍历数组查找查找超过一年的书籍
        for (int i = 0; i < countbook; i++) {
            //3.1获取时间上架时间
            LocalDate shelfTime = books[i].getShelfDatel();
            //3.2获取是否上架超过一年
            long shelfYearTime = ChronoUnit.YEARS.between(shelfTime,localDate);
            //3.3超过一年是否移除
            if(shelfYearTime > 1){
                System.out.println("书籍名称：《" + books[i].getTitle() + "》已经上架超过一年，是否删除：（1.Yes 2.No)" );
                System.out.print("请输入你的选择：");
                int choice = scanner.nextInt();
                if(choice == 1){
                    if(books[i].getIsBorrowed() == true){
                        System.out.println("不可移除！");
                    }else{
                         removeBook(i);
                         i--;
                    }
                }
            }
        }
    }

    //借阅图书
    public void borrowed(int pos){

            books[pos].setBorrowed(true);
            books[pos].setBorrowCount(books[pos].getBrorrowCount() + 1);

        System.out.println("图书：《" + books[pos].getTitle() +"》借阅成功！");
        //将书籍借阅人ID和书籍编号存入数组
        storeBook();
    }
    //归还图书
    public void returnBook(int pos){

        books[pos].setBorrowed(false);

        System.out.println("图书：《" + books[pos].getTitle() +"》归还成功！");
        //将书籍借阅人ID和书籍编号存入数组
        storeBook();
    }
    //展示个人借阅情况
    public void viewBorrowedBook(int i) {
        System.out.println("借阅书籍名称：" + books[i].getTitle() + " 借阅次数：" +
         books[i].getBrorrowCount());
    }
    //退出系统
       public void systemExit(){

         System.exit(0);
       }

}
